/********************************************************/
/*	Copyright (C) 2016 Gong Li Bin		 	*/
/*	Project:	GlbLib-1.0.0			*/
/*	Author:		gong_libin			*/
/*	Date:		2016_06_01			*/
/*	File:		GlbPipe.cpp			*/
/********************************************************/

#include "GlbPipe.h"

namespace GlbCls
{

CGlbPipe::CGlbPipe()
{
	m_pstPipe = NULL;
	m_pszResult = NULL;
}

CGlbPipe::~CGlbPipe()
{
	m_pstPipe = NULL;
	m_pszResult = NULL;
}

void CGlbPipe::GlbPipeClose()
{
	if (NULL != m_pstPipe) {
		pclose(m_pstPipe);
	}

	return;
}

char* CGlbPipe::GlbPipeResultGet()
{
	return m_pszResult;
}

void CGlbPipe::GlbPipeResultFree()
{
	if (NULL != m_pszResult) {
		free(m_pszResult);
		m_pszResult = NULL;
	}

	return;
}

void CGlbPipe::GlbPipeResultReset(ULONG ulSize)
{
	ULONG ulLength = 0;

	if (NULL != m_pszResult) {
		ulLength = ulSize ? ulSize : GLB_PIPE;
		memset(m_pszResult, '\0', sizeof(char) * ulLength);
	}

	return;
}

int CGlbPipe::GlbPipeResultMalloc(ULONG ulSize)
{
	ULONG ulLength = 0;

	ulLength = ulSize ? ulSize : GLB_PIPE;
	if (NULL != (m_pszResult = (char*)malloc(sizeof(char) * ulLength))) {
		memset(m_pszResult, '\0', sizeof(char) * ulLength);
	}
	else {
		return GLB_FAILURE;
	}

	return GLB_SUCCESS;
}

int CGlbPipe::GlbPipeOpen(char* pszGlbd, char* pszType)
{
	m_pstPipe = popen(pszGlbd, pszType);

	if (NULL == m_pstPipe) {
		GLB_ERROR("%s\n", strerror(errno));
		return GLB_FAILURE;
	}

	return GLB_SUCCESS;
}

ULONG CGlbPipe::GlbPipeRead(ULONG ulSize)
{
	ULONG ulCount = 0;
	char szPacket[GLB_PACKET] = { 0 };

	if (NULL != m_pszResult) {
		while (NULL != fgets(szPacket, GLB_PACKET, m_pstPipe)) {
			ulCount += strlen(szPacket);
			if (ulCount < ulSize) {
				strcat(m_pszResult, szPacket);
				memset(szPacket, '\0', GLB_PACKET);
			}
		}
	}

	return ulCount;
}

} /* GlbCls */
